package com.rapida.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;

/**
 * Created by mm on 2015/1/19.
 */
public class SQLiteHelper extends SQLiteOpenHelper {
	private static final String USER_DB_NAME = "rapid.db";
	private static final HashMap<Class<?>, String> CLASS_TYPES = new HashMap<Class<?>, String>();
	private HashMap<String, Class<?>> COLUMN = new HashMap<String, Class<?>>();
	private String USER_TABLE_NAME;

	static {
		CLASS_TYPES.put(String.class, "TEXT");
		CLASS_TYPES.put(Integer.class, "INTEGER");
	}

	public SQLiteHelper(Context context, String tablename, HashMap<String, Class<?>> column) {
		super(context, USER_DB_NAME, null, 1);
		USER_TABLE_NAME = tablename;
		COLUMN.putAll(column);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		StringBuilder sql = new StringBuilder();
		sql.append("CREATE TABLE " + USER_TABLE_NAME);
		sql.append(" (");
		COLUMN.remove("_index");
		sql.append("_index INTEGER PRIMARY KEY AUTOINCREMENT,");
		Iterator iterator = COLUMN.entrySet().iterator();
		while (iterator.hasNext()) {
			TreeMap.Entry entry = (TreeMap.Entry) iterator.next();
			sql.append(entry.getKey() + " " + CLASS_TYPES.get(entry.getValue()));
			sql.append(",");
		}
		sql.deleteCharAt(sql.length() - 1);
		sql.append(")");
		db.execSQL(sql.toString());
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("ALTER TABLE " + USER_TABLE_NAME + " ADD COLUMN other TEXT");
	}
}
